﻿
using System;
using System.Threading;

namespace Demo.Test.Times
{

    /// <summary>
    /// 定时器 -- 安全, 加个定时器停止标识
    /// </summary>
    public class SafeTimes
    {
        /// <summary>
        /// 定时器实例
        /// </summary>
        static System.Threading.Timer Time;

        /// <summary>
        /// 定时器延时时间
        /// </summary>
        static Int32 DelayTime;

        /// <summary>
        /// 定时器间隔时间
        /// </summary>
        static Int32 IntervalTime;

        /// <summary>
        /// 定时器运行次数
        /// </summary>
        static Int32 RunTime;

        /// <summary>
        /// 定时器运行睡眠时间
        /// </summary>
        static Int32 RunSleep;

        /// <summary>
        /// 定时器是否启用
        /// </summary>
        static bool IsEnable = true;

        /// <summary>
        /// 定时器共享变量
        /// </summary>
        public static Int32 Count;

        /// <summary>
        /// 对象锁
        /// </summary>
        static object ObjLock = new object();

        /// <summary>
        /// 初始化定时器并开始执行
        /// </summary>
        /// <param name="delayTime">定时器延时开始时间</param>
        /// <param name="intervalTime">定时器间隔执行时间</param>
        /// <param name="runTime">定时器运行次数</param>
        /// <param name="runSleep">定时器运行每次睡眠时间</param>
        public static void Init(Int32 delayTime, Int32 intervalTime, Int32 runTime, Int32 runSleep)
        {
            ThreadPool.SetMaxThreads(100, 10);
            DelayTime = delayTime;
            IntervalTime = intervalTime;
            RunTime = runTime;
            RunSleep = runSleep;
            Time = new Timer(Execute, null, DelayTime, IntervalTime);
        }

        static void Execute(object obj)
        {
            lock (ObjLock)
            {
                if (!IsEnable)
                {
                    return;
                }
                Thread.Sleep(RunSleep);
                Count++;
                if (Count == RunTime)
                {
                    Time.Dispose();
                    IsEnable = false;
                }
                System.Diagnostics.Debugger.Log(1, "", "定时器：打印" + Count + "次\n");
            }
        }
    }

}
